package Domain.MySqlAccessors;

import java.util.Collection;
import java.util.LinkedList;
import java.sql.ResultSet;
import java.sql.SQLException;

import Persistance.MySqlUtilityManagment;
import Persistance.PrintfFormat;
import org.apache.log4j.Logger;
import BusinessLogic.Exceptions.DataAlreadyExistException;

public abstract class MySqlProxy<T> {

    static Logger logger = Logger.getLogger("MovieSystem.Domain.MySqlAccessors.MySqlProxy");

    protected MySqlUtilityManagment m_sql;
    protected String TABLE_NAME;
    protected String KEY_COLUMN_NAME;
    protected String ALL_COLUMN_NAMES;

    public MySqlProxy(MySqlUtilityManagment sql) {
        m_sql = sql;
    }

    public abstract T toRecordType(ResultSet rs) throws SQLException;
    public abstract String toValues(T record);

    public void addRecord(T record) throws DataAlreadyExistException {
        String values = toValues(record);
        m_sql.addData(TABLE_NAME,ALL_COLUMN_NAMES,values);
    }

    public void deleteRecord(String key) {
        String filter = new PrintfFormat(KEY_COLUMN_NAME).sprintf(key.split(","));
        m_sql.deleteData(TABLE_NAME,filter);
    }

    public T getRecord(String key) {
        String filter = new PrintfFormat(KEY_COLUMN_NAME).sprintf(key.split(","));        
        ResultSet rs = m_sql.getData(TABLE_NAME,filter);
        T res = null;
        try {
            rs.first();
            res = toRecordType(rs);
            rs.close();
        }
        catch (SQLException e) {
            logger.info("No such record "+key);
        }
        return res;
    }

    public Collection<T> searchRecords(String filter) {
        ResultSet rs = m_sql.getData(TABLE_NAME,filter);
        Collection<T> result = new LinkedList<T>();
        try {
            while(rs.next())
                result.add(toRecordType(rs));
            rs.close();
        }
        catch (SQLException e) {
            logger.info(e.getMessage(),e);            
        }
        return result;
    }

    public Collection<T> searchRecords(String filter, int start, int amount) {
        ResultSet rs = m_sql.getData(TABLE_NAME,filter,start,amount);
        Collection<T> result = new LinkedList<T>();
        try {
            while(rs.next())
                result.add(toRecordType(rs));
            rs.close();
        }
        catch (SQLException e) {
            logger.info(e.getMessage(),e);
        }
        return result;
    }

}
